﻿
using Microsoft.EntityFrameworkCore;
using System.Reflection.Metadata;

namespace nhCore.db;

public class EnvDbContext : DbContext
{
    public const string con_str_conn_str = "Data Source=nh.db";

    public DbSet<ElementConfig> ElementConfigs { get; set; }
    public DbSet<Station> Stations { get; set; }
    public DbSet<FSetting> FSettings { get; set; }
    public DbSet<Data> Datas { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
           => options.UseSqlite(con_str_conn_str);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        //数据库种子数据
        modelBuilder.Entity<Station>().HasData(
            new Station() 
            {
                Id = 1,
                Name = "自动气象站",
                HandshakeFrame = "0100", 
            });

        modelBuilder.Entity<ElementConfig>().HasData(
            [
                new ElementConfig()
                {
                    Id = 1,
                    StationId = 1,
                    MappingStationId = 1,
                    StationReg = 3,
                    DeviceAddress = 0x08,
                    RegAddress = 0x03,
                    FunctionCode = 0x03,
                    Name = "气温",
                    Unit = "℃",
                    DataType = NDataType.con_2ByteInt,
                    Digits = 1,
                    Statistics = ElementConfig.con_AVG,
                },
                new ElementConfig()
                {
                    Id = 2,
                    StationId = 1,
                    MappingStationId = 1,
                    StationReg = 4,
                    DeviceAddress = 0x08,
                    RegAddress = 0x04,
                    FunctionCode = 0x03,
                    Name = "气湿",
                    Unit = "%",
                    DataType = NDataType.con_2ByteInt,
                    Digits = 1,
                    Statistics = ElementConfig.con_AVG,
                },
            ]);

        List<FSetting> settingList = [];  
        foreach (var data in NSetting.Dic种子数据)
        {
            settingList.Add(
                new FSetting(data.Key, data.Value));
        }
        modelBuilder.Entity<FSetting>().HasData(settingList
            );
    }
}